import { filterAuth } from '@/support/common';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, Input, message, Modal, Popconfirm, Select } from 'antd';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import React, { Fragment } from 'react';
import enums from '../../../../public/enums';

const { Option } = Select;
const FormItem = Form.Item;
const { TextArea } = Input;
const formItemLayout = {
  labelCol: {
    xs: { span: 12 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 4 },
    sm: { span: 14 },
  },
};
@Form.create()
@connect((state: any) => ({
  org: state.org,
  user: state.user,
}))
export default class Add extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      visible: false,
      formData: {}, // 编辑有数据，新增无
    };
  }

  static contextTypes = {
    permissions: PropTypes.array,
  };

  showModal = () => {
    this.setState({
      visible: true,
    });
  };
  // 全新的写法，可以用props数据来设置state
  handleEdit = () => {
    this.setState((state: any, props: any) => ({ visible: true, formData: props.details }));
  };

  handleCreate = () => {
    const {
      form: { validateFields },
      dispatch,
      details,
    } = this.props;
    const { formData } = this.state;
    validateFields((err: any, values: any) => {
      if (err) {
        return;
      }
      // 添加编辑处理逻辑
      if (!!formData.sid) {
        const submitData = {
          orgCode: values.orgCode,
          orgName: values.orgName,
          orgType: values.orgType,
          orgDesc: values.orgDesc,
        };
        dispatch({
          type: 'base/add',
          payload: { url: '/org/edit', ...submitData },
          callback: (response: any) => {
            message.success('编辑成功');
            this.handleCancel();
            this.props.hanldClearDetails();
            dispatch({
              type: 'org/fetchTree',
            });
          },
        });
      } else {
        // 新增逻辑处理，不做改动
        if (details && details.sid) {
          values.orgParent = details.sid;
        } else {
          delete values.orgParent;
        }
        dispatch({
          type: 'org/add',
          payload: values,
          callback: (response: any) => {
            if (response.statusCode === '0') {
              this.setState({ visible: false });
              message.success('添加成功');
              dispatch({
                type: 'org/fetchTree',
              });
            } else {
              this.setState({ visible: true });
            }
          },
        });
      }
    });
  };

  handleCancel = () => {
    this.props.form.resetFields();
    this.setState({
      visible: false,
      formData: {},
    });
  };

  hanldeRemove = (orgCode: any) => {
    const { dispatch, changeDelOrg } = this.props;
    dispatch({
      type: 'org/remove',
      payload: { orgCode: orgCode },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          changeDelOrg();
          this.props.hanldClearDetails();
        }
      },
    }).then(() => {
      dispatch({
        type: 'org/fetchTree',
      });
    });
  };

  render() {
    const {
      pathname,
      form: { getFieldDecorator },
      details,
      delOrg,
      parentOrgType,
    } = this.props;

    const { visible, formData } = this.state;
    const permissions = this.context.permissions;
    console.log(enums.orgType.array);
    return (
      <Fragment>
        <p style={{ marginBottom: 12 }}>
          {filterAuth('org_doAdd', permissions, pathname) && delOrg && (
            <Button icon={<PlusOutlined />} size="small" type="primary" onClick={this.showModal}>
              新增
            </Button>
          )}
          {filterAuth('org_doAdd', permissions, pathname) &&
            delOrg &&
            filterAuth('org_doDel', permissions, pathname) &&
            !details.isRoot &&
            !details.isMerchant && <Divider type="vertical" />}
          {/* {delOrg && filterAuth('org_doDel', permissions, pathname) && details.orgLevel !== 1 && ( */}
          {delOrg &&
            filterAuth('org_doDel', permissions, pathname) &&
            !details.isRoot &&
            // 商户组织不允许删除
            !details.isMerchant && (
              <Popconfirm
                title="是否确认移除此组织？"
                onConfirm={() => this.hanldeRemove(details.orgCode)}
              >
                <Button size="small" type="primary">
                  删除
                </Button>
              </Popconfirm>
            )}
          {filterAuth('org_doDel', permissions, pathname) &&
            delOrg &&
            filterAuth('org_doEdit', permissions, pathname) &&
            !details.isRoot &&
            // 商户组织不允许编辑
            !details.isMerchant && <Divider type="vertical" />}
          {delOrg &&
            filterAuth('org_doEdit', permissions, pathname) &&
            !details.isRoot && // 商户组织不允许编辑
            !details.isMerchant && (
              <Button size="small" type="primary" onClick={this.handleEdit}>
                编辑
              </Button>
            )}
        </p>
        <Modal
          title={<span>{formData.sid ? '编辑' : '新增'}</span>}
          visible={visible}
          onOk={() => {
            this.handleCreate();
          }}
          okText="保存"
          cancelButtonProps={{ size: 'small' }}
          okButtonProps={{ size: 'small' }}
          onCancel={() => {
            this.handleCancel();
          }}
          width={600}
        >
          <div id="orgForm">
            <Form layout="horizontal">
              {formData.sid ? null : (
                <FormItem
                  {...formItemLayout}
                  label={<span>所属上级&nbsp;</span>}
                  // hasFeedback
                  // required
                >
                  {getFieldDecorator('orgParent', {
                    initialValue: !formData.sid ? details.orgName : formData.orgParentName,
                  })(<Input disabled />)}
                </FormItem>
              )}

              <FormItem
                {...formItemLayout}
                label={<span>组织名称&nbsp;</span>}
                // hasFeedback
              >
                {getFieldDecorator('orgName', {
                  rules: [{ required: true, message: '请输入组织名称' }],
                  initialValue: formData.orgName,
                })(<Input placeholder="请输入组织名称" />)}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label={<span>组织编码&nbsp;</span>}
                // hasFeedback
              >
                {getFieldDecorator('orgCode', {
                  rules: [
                    {
                      required: true,
                      message: '请输入组织编码',
                      // message: '由数字、26个英文字母或者下划线组成的2-40位字符!',
                      // pattern: /^[\w]{2,40}$/,
                    },
                  ],
                  initialValue: formData.orgCode,
                })(
                  <Input
                    placeholder="请输入组织编码"
                    maxLength={100}
                    disabled={!!formData.orgCode}
                  />,
                )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label={<span>组织类型&nbsp;</span>}
                // hasFeedback
              >
                {getFieldDecorator('orgType', {
                  rules: [{ required: true, message: '请选择组织类型' }],
                  initialValue: formData.orgType,
                })(
                  // 组织类型不可修改
                  //  组织类型为主机厂或空，则下级组织可以建主机厂/商户/经销商；若组织类型为商户，则下级组织只能建商户；若组织类型为经销商，下级组织只能建经销商
                  <Select allowClear placeholder="请选择组织类型" disabled={!!formData.sid}>
                    {enums.orgType.array
                      .filter((item) => {
                        return [2, 3].includes(parentOrgType) ? item.value === parentOrgType : true;
                      })
                      .map((option) => {
                        return (
                          <Option key={option.value} value={option.value}>
                            {option.label}
                          </Option>
                        );
                      })}
                  </Select>,
                )}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label={<span>组织简介&nbsp;</span>}
                // hasFeedback
              >
                {getFieldDecorator('orgDesc', {
                  initialValue: formData.orgDesc,
                })(<TextArea placeholder="请输入组织简介" rows={4} />)}
              </FormItem>
            </Form>
          </div>
        </Modal>
      </Fragment>
    );
  }
}
